package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"tieba/models/cache"
	"tieba/models/mysql"
	"time"

	"tieba/tiebarpc/internal/svc"
	"tieba/tiebarpc/tiebarpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type TopLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TopLogic {
	return &TopLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TopLogic) Top(in *tiebarpc.TopRequest) (*tiebarpc.TopResponse, error) {
	// todo: add your logic here and delete this line
	var a []mysql.TieZi
	key := fmt.Sprintf("热度排行榜top10")
	result, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if result != "" {
		json.Unmarshal([]byte(result), &a)
	} else {
		mysql.DB.Debug().Order("tie_zis.likes desc").Limit(10).Find(&a)
		jsonData, _ := json.Marshal(&a)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*10)
	}

	var b []*tiebarpc.TopList
	for _, c := range a {
		list := tiebarpc.TopList{
			TieZiId: int64(c.ID),
			TieId:   c.TieId,
			UserId:  c.UserId,
			Title:   c.Title,
			Content: c.Content,
			Likes:   c.Likes,
		}
		b = append(b, &list)
	}
	return &tiebarpc.TopResponse{List: b}, nil
}
